﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Shared.Model;
using Client;
using ManageSystem.Dialog;

namespace ManageSystem.Manager
{
    public partial class FormOrder : UserControl
    {
        List<YCD_ORDER> _listOrder = null;
        YCD_ORDER _selectedOrder = null;

        private bool _finished = false;
        private bool _canDist = false;
        public FormOrder(bool finished,bool canDist)
        {
            _finished = finished;
            _canDist = canDist;
            InitializeComponent();
        }

        private void ClearText()
        {
            this.textBoxOrderSn.Clear();
            this.textBoxOrderNum.Clear();
            this.textBoxProductCode.Clear();
            this.textBoxProductType.Clear();
            this.textBoxProvince.Clear();
            this.textBoxFullProductNum.Clear();
        }

        private void SetText(YCD_ORDER order)
        {
            if (order == null) return;
            this.textBoxOrderSn.Text = order.ORDER_SN;
            this.textBoxProductCode.Text = order.PRODUCT_CODE;
            this.textBoxProductType.Text = order.DEVICE_TYPE;
            this.textBoxProvince.Text = order.PROVINCE;
            this.textBoxOrderNum.Text = order.NUMBER.ToString();
            this.textBoxFullProductNum.Text = order.PRODUCT_NUMBER.ToString();
        }

        private void SetListViewOrder(YCD_ORDER order)
        {
            if (order == null) return;
            ListViewItem item = new ListViewItem();
            item.Text = order.ID.ToString();
            item.SubItems.Add(order.ORDER_SN);
            item.SubItems.Add(order.PRODUCT_CODE);
            item.SubItems.Add(order.PROVINCE);
            item.SubItems.Add(order.DEVICE_TYPE);
            item.SubItems.Add(order.NUMBER.ToString());
            item.SubItems.Add(order.PRODUCT_NUMBER.ToString());

            if (order.DROPED)
                item.SubItems.Add("作废");
            else
                item.SubItems.Add("有效");

            this.listViewOrder.Items.Add(item);
        }
        
        private void ClearListViewOrder()
        {
            this.listViewOrder.Items.Clear();
        }

        private void FormOrder_Load(object sender, EventArgs e)
        {
            ClearListViewOrder();
            ClearText();

            YCD_ORDER orderW = new YCD_ORDER();
            orderW.SetWhere();

            orderW.FINISHED = _finished;
            //orderW.DROPED = false;

            var selectOrder = MethodWcf.SelectOrderClient(orderW);

            if (selectOrder.result)
            {
                _listOrder = (from o in selectOrder.value
                              orderby o.DROPED
                              orderby o.ID descending
                              select o).ToList();

                for(int i = 0; i < _listOrder.Count; i++)
                {
                    SetListViewOrder(_listOrder[i]);
                }
            }
        }
        //作废订单
        private void buttonDrop_Click(object sender, EventArgs e)
        {
            //for (int i = 0; i < 200; i++)
            //    Task.Factory.StartNew(() =>
            //    {
            //        MethodWcf.GetYcdMacClient("EPON");
            //    });

            //return;

            if (_selectedOrder == null) return;

            if (MessageBox.Show("是否作废订单？", "提示", MessageBoxButtons.YesNo) == DialogResult.No) return;
            if (MessageBox.Show("是否作废订单？", "提示", MessageBoxButtons.YesNo) == DialogResult.No) return;

            //判断MAC地址是否已经上传了，若已经上传了则不能作废
            Device_Data deviceW = new Device_Data();
            deviceW.SetWhere();
            deviceW.ORDER_SN = _selectedOrder.ORDER_SN;
            var selectCountDevice = MethodWcf.SelectDeviceDataCountClient(deviceW);
            if (selectCountDevice.message != "0")
            {
                MessageBox.Show("已上传订单对应的MAC地址，不能作废订单");
                return;
            }

            //已分配SN的订单不可以作废
            PRODUCT_SN proSnW = new PRODUCT_SN();
            proSnW.SetWhere();
            proSnW.ORDER_SN = _selectedOrder.ORDER_SN;
            var selectProSnCount = MethodWcf.SelectProductSnCountClient(proSnW);
            if (selectProSnCount.message != "0")
            {
                MessageBox.Show("已生成SN号码，不能作废订单");
                return;
            }

            _selectedOrder.SetWhere();
            _selectedOrder.ID = _selectedOrder.ID;
            _selectedOrder.SetUpdate();
            //if (SetOrder(_selectedOrder) == false) return;
            _selectedOrder.DROPED = true;

            var updateOrder = MethodWcf.UpdateOrderClient(_selectedOrder);
            if (updateOrder.result)
            {
                MessageBox.Show("作废成功");
            }
            else
            {
                MessageBox.Show("作废失败");
            }

            FormOrder_Load(null, null);
            _selectedOrder = null;
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            YCD_ORDER order = new YCD_ORDER();
            order.SetUpdate();
            if (SetOrder(order) == false)  return;

            var insertOrder = MethodWcf.InsertOrderClient(order);
            if (insertOrder.result)
            {
                MessageBox.Show("添加成功");

                if (MessageBox.Show("是否生成订单对应的SN号？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    this.buttonCreateSn.PerformClick();
                }
            }
            else
            {
                MessageBox.Show("添加失败");
            }

            FormOrder_Load(null, null);
        }

        private bool SetOrder(YCD_ORDER order)
        {
            if (order == null) return false;
            string orderSn = this.textBoxOrderSn.Text.Trim();
            string orderNum = this.textBoxOrderNum.Text.Trim();
            string orderProCode = this.textBoxProductCode.Text.Trim();
            string orderDeviceType = this.textBoxProductType.Text.Trim();
            string orderProvince = this.textBoxProvince.Text.Trim();
            string fullProductNum = this.textBoxFullProductNum.Text.Trim();

            if(string.IsNullOrEmpty(orderSn)
                ||string.IsNullOrEmpty(orderNum)
                || string.IsNullOrEmpty(orderProCode)
                ||string.IsNullOrEmpty(orderDeviceType)
                || string.IsNullOrEmpty(orderProvince)
                ||string.IsNullOrEmpty(fullProductNum))
            {
                MessageBox.Show("输入数据错误，不能为空");
                return false;
            }

            //给出信息提示
           var enterRet= MessageBox.Show(
                string.Format("订单号：{0}\r\n产品编码：{1}\r\n省份代码：{2}\r\n产品类型：{3}\r\n订单数量：{4}\r\n栈板产品数量：{5}",orderSn,orderProCode,orderProvince,orderDeviceType,orderNum,fullProductNum),
                "确认信息是否正确",
                MessageBoxButtons.OKCancel,
                 MessageBoxIcon.Warning);

            if (enterRet == DialogResult.Cancel) return false;

            order.ORDER_SN = orderSn;

            int num;
            if (int.TryParse(orderNum, out num) == false || num % 20 != 0)
            {
                MessageBox.Show("订单数量不正确");
                return false;
            }
            order.NUMBER = num;

            if (int.TryParse(fullProductNum, out num) == false || num % 20 != 0)
            {
                MessageBox.Show("栈板产品数量不正确");
                return false;
            }
            order.PRODUCT_NUMBER = num;

            order.PRODUCT_CODE = orderProCode;
            order.DEVICE_TYPE = orderDeviceType;
            order.PROVINCE = orderProvince;
            return true;
        }

        private void textBoxSearch_TextChanged(object sender, EventArgs e)
        {
            ClearListViewOrder();
            string searchText = this.textBoxSearch.Text.Trim();
            if (string.IsNullOrEmpty(searchText))
            {
                for(int i = 0; i < _listOrder.Count; i++)
                {
                    SetListViewOrder(_listOrder[i]);
                }
                return;
            }

            var listSearch = (from o in _listOrder
                              where string.Format("{0}|{1}|{2}|{3}|{4}|{5}"
                              ,o.ORDER_SN
                              ,o.NUMBER
                              ,o.PRODUCT_CODE
                              ,o.PROVINCE
                              ,o.DEVICE_TYPE
                              ,o.FINISHED).Contains(searchText)
                              orderby o.ID descending
                              select o).ToList();

            if (listSearch == null || listSearch.Count == 0) return;

            for(int i = 0; i < listSearch.Count; i++)
            {
                SetListViewOrder(listSearch[i]);
            }
        }

        private void listViewOrder_MouseClick(object sender, MouseEventArgs e)
        {
            ClearText();

            if (this._listOrder.Count == 1)
            {
                _selectedOrder = _listOrder[0];
                SetText(_selectedOrder);
                return;
            }

            var selected = this.listViewOrder.SelectedItems;
            if (this.listViewOrder.Items.Count >= 1 && selected.Count == 1)
            {
                _selectedOrder = (from o in _listOrder
                                  where o.ID == int.Parse(selected[0].Text)
                                  select o).FirstOrDefault();

                SetText(_selectedOrder);
            }
        }

        private void textBoxProvince_Enter(object sender, EventArgs e)
        {
            DialogProvince province = new DialogProvince(this.textBoxProvince);
            province.ShowDialog();
        }

        private void textBoxProductType_Enter(object sender, EventArgs e)
        {
            DialogDeviceType type = new DialogDeviceType(this.textBoxProductType);
            type.ShowDialog();
        }

        private void buttonCreateSn_Click(object sender, EventArgs e)
        {
            //生成SN号码
            //if (_selectedOrder == null) return;
            string orderSn = this.textBoxOrderSn.Text.Trim();
            if (string.IsNullOrEmpty(orderSn)) return;
            string sql = string.Format("DECLARE	@message varchar(200)  EXEC	[dbo].[Proc_DistributeOrderSn] 	@order_sn = N'{0}', @message = @message OUTPUT",orderSn);
            int executeNum = 0;
            if ((executeNum = MethodWcf.ExecuteSQLClient(sql)) > 0)
            {
                MessageBox.Show("分配成功，分配数量为："+executeNum);
            }
            else
            {
                MessageBox.Show("分配失败，SN已分配或订单已作废");
            }
            ClearText();
        }

        private void listViewOrder_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //显示订单分号详情
            var selected = this.listViewOrder.SelectedItems;
            if (this.listViewOrder.Items.Count >= 1 && selected.Count == 1)
            {
                _selectedOrder = (from o in _listOrder
                                  where o.ID == int.Parse(selected[0].Text)
                                  select o).FirstOrDefault();

                PRODUCT_SN_LOG logW = new PRODUCT_SN_LOG();
                logW.ORDER_SN = _selectedOrder.ORDER_SN;
                logW.SetWhere(string.Format("ORDER_SN='{0}' AND LOG_TIME>='{1}' ORDER BY ID DESC", _selectedOrder.ORDER_SN,DateTime.Now.AddDays(-30).Date));

                FormProductSnLog log = new FormProductSnLog(logW, _selectedOrder.FINISHED,_canDist);
                log.ShowDialog();
            }
        }
    }
}
